package com.yanze.schoolinformation.viewModule.school_news;

import android.content.Context;

import com.yanze.schoolinformation.app.C;
import com.yanze.schoolinformation.model.bean.SchoolNewsBean;
import com.yanze.schoolinformation.model.http.DeforSubscriber;
import com.yanze.schoolinformation.utils.ToastUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.reactivestreams.Subscription;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by MrZheng on 2018/4/28.
 */

public class SchoolNewsViewModel {
    private int pageCount = 14;//默认每页条目数，若不够14则视为最后一页
    private int lastCount = 14;//上一次请求回的条目数
    private String loadUrl;
    private int page = 1;
    private Subscription mSubscription;
    private SchoolNewsNavigator mNavigator;
    private Context mContext;

    public SchoolNewsViewModel(Context mContext) {
        this.mContext = mContext;
    }

    public void setLoadUrl(String loadUrl) {
        this.loadUrl = loadUrl;
    }

    public void setmNavigator(SchoolNewsNavigator mNavigator) {
        this.mNavigator = mNavigator;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void getSchoolNewsList() {
        if (lastCount < pageCount) {//上一次请求回的新闻条目数比14条少，就认为上次是最后一页
            mNavigator.noMoreData();
        }
        Flowable.create(new FlowableOnSubscribe<List<SchoolNewsBean>>() {
            @Override
            public void subscribe(@NonNull FlowableEmitter<List<SchoolNewsBean>> d) throws Exception {
                try {
//                    if (CheckNetwork.isNetworkConnected(mContext)) {
                        List<SchoolNewsBean> schoolNews = loadData();
                        d.onNext(schoolNews);
                        d.onComplete();
//                    }else{
//                        d.onError(new ConnectException());
//                    }
                } catch (IOException e) {
                    d.onError(e);
                    e.printStackTrace();
                }
            }
        }, BackpressureStrategy.BUFFER)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new DeforSubscriber<List<SchoolNewsBean>>() {
                    @Override
                    public void _onSubscribe(Subscription s) {
                        mSubscription = s;
                    }

                    @Override
                    public void _onNext(List<SchoolNewsBean> schoolNewsBeen) {
                        mNavigator.showSuccessView();
                        if (page == 1) {
                            if (schoolNewsBeen != null
                                    && schoolNewsBeen.size() > 0) {
                                lastCount = schoolNewsBeen.size();
                                //刷新操作
                                mNavigator.setAdapterData(schoolNewsBeen);
                            }else{
                                mNavigator.loadDataFaild();
                            }
                        }else{
                            if (schoolNewsBeen != null
                                    && schoolNewsBeen.size() > 0) {
                                lastCount = schoolNewsBeen.size();
                                mNavigator.setLoadMore(schoolNewsBeen);
                            }else{
                                mNavigator.noMoreData();
                            }
                        }
                    }

                    @Override
                    public void _onError(String errmsg) {
                        ToastUtils.show(errmsg);
                        mNavigator.loadDataFaild();
                        if (page > 1) {
                            page--;
                        }
                    }
                });
    }

    private List<SchoolNewsBean> loadData() throws IOException {
        //http://xhxy.cumt.edu.cn/ + 4501/ + list1 + .htm
        String baseUrl = C.url.XuHaiUrl + loadUrl + "list" + page + C.url.XuHaiUrlEnd;
        List<SchoolNewsBean> tempList = new ArrayList<>();
        Document document = Jsoup.connect(baseUrl).timeout(5000).get();
        Element container = document.getElementsByClass("wp-wrapper wp-container").first();
        Element container1 = container.getElementsByTag("div").first();
        Element news_container = container1.getElementsByClass("wp-column-news").first();
        Element news_container1 = news_container.getElementsByTag("div").first();
        Element newsContainer = news_container1.getElementsByClass("column-news-con").first();
        Element newsContainer1 = newsContainer.getElementsByTag("div").first();
        Element news_list = newsContainer1.getElementById("wp_news_w9");
        Elements newsList = news_list.getElementsByTag("a");
        for (Element a : newsList) {
            String href = a.attr("href");
            Element titleSpan = a.getElementsByClass("column-news-title").first();
            String title = titleSpan.text();
            Element timeSpan = a.getElementsByClass("column-news-date news-date-hide").first();
            String time = timeSpan.text();
            tempList.add(new SchoolNewsBean(title, href, time));
        }
        return tempList;
    }

    public void onDestory() {
        if (mSubscription != null) {
            mSubscription.cancel();
        }
        mNavigator = null;
    }
}
